package com.imon.meere;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.imon.meere.dao.Vehicle;
import com.imon.meere.dao.VehicleDao;

/**
 * Hello world!
 * 
 */
public class App {
	private static final Log LOG = LogFactory.getLog(App.class);

	public static void main(final String[] args) throws InterruptedException {
		new App().run();
	}

	private void run() throws InterruptedException {
		LOG.debug("Running application");
		final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		testVehicleDao(applicationContext);
		applicationContext.close();
	}

	private void testVehicleDao(final AbstractApplicationContext applicationContext) throws InterruptedException {
		final VehicleDao dao = applicationContext.getBean(VehicleDao.class);
		dao.deleteAll();
		dao.beginConnection();

		final CountDownLatch latch = new CountDownLatch(1);
		final ExecutorService executor = Executors.newSingleThreadExecutor();

		executor.execute(new Runnable() {

			@Override
			public void run() {
				LOG.debug("Inserting record into database");
				int count = 1;
				while (true) {
					final Vehicle vehicle = new Vehicle("V" + count++, "RED", 4, 2);
					dao.insert(vehicle);
				}

			}
		});

		latch.await(15, TimeUnit.SECONDS);
		dao.endConnection();
		LOG.debug("Stopping application");
		System.exit(0);
		executor.shutdownNow();
	}
}
